<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>leaflet克里金空间插值</title>
    <style>
        html, body, #map {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
            cursor: default;
        }
    </style>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"/>
    <script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script>
    <script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"></script>
    <script src="https://unpkg.com/esri-leaflet@2.2.4/dist/esri-leaflet.js"></script>
    <script src="kriging.js"></script>
    <script src="point.js"></script>
    <script src="world.js"></script>
</head>
<body>
<canvas id="canvasMap" style="display: none;" ></canvas>
<div id="map"></div>
<script>
  var map = L.map('map', {
    center: [38.65953686, 120.8696333],
    zoom: 9
  });

  L.esri.tiledMapLayer({
    url: 'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}'
  }).addTo(map);

  //world.js,是插值之后需要裁切的图形边界信息
  //point.js,是要插值的离散的点


  //遍历world边界数据，生成scope边界线
  var positions = [];
  world[0].forEach(function (point) {
    positions.push([point[1], point[0]]);
  });
  var scope = L.polyline(positions, {color: 'red'}).addTo(map);
  map.fitBounds(scope.getBounds());

  //根据scope边界线的范围，计算范围变量
  var xlim =[scope.getBounds()._southWest.lng,scope.getBounds()._northEast.lng];
  var ylim =[scope.getBounds()._southWest.lat,scope.getBounds()._northEast.lat];


  //进行克里金插值
  function loadkriging()
  {
    var canvas = document.getElementById("canvasMap");
    canvas.width = 1000;
    canvas.height = 1000;
    var n = points.length;
    var t = [];//数值
    var x = [];//经度
    var y = [];//纬度
    for (var i = 0; i < n; i++)
    {
      t.push(points[i].attributes.TN_);
      x.push(points[i].geometry.x);
      y.push(points[i].geometry.y);
      L.circle([y[i], x[i]], {radius: 1}).addTo(map);
    }

    //对数据集进行训练
    var variogram = kriging.train(t, x, y, "exponential", 0, 100);

    //使用variogram对象使polygons描述的地理位置内的格网元素具备不一样的预测值,最后一个参数，是插值格点精度大小
    var grid = kriging.grid(world, variogram, (ylim[1]-ylim[0])/150);

    var colors = ["#006837", "#1a9850", "#66bd63", "#a6d96a", "#d9ef8b", "#ffffbf", "#fee08b", "#fdae61", "#f46d43", "#d73027", "#a50026"];
    //将得到的格网grid渲染至canvas上
    kriging.plot(canvas, grid, [xlim[0], xlim[1]], [ylim[0], ylim[1]], colors);
  }

  //将canvas对象转换成image的URL
  function returnImgae() {
    var mycanvas = document.getElementById("canvasMap");
    return mycanvas.toDataURL("image/png");
  }

  loadkriging();

  var imageBounds =[[ylim[0], xlim[0]], [ylim[1], xlim[1]]];
  L.imageOverlay(returnImgae(), imageBounds, {opacity: 0.8}).addTo(map);


</script>
</body>
</html>